package com.codeant.bikeindicatorapplication.tools;

import static android.content.Context.LOCATION_SERVICE;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.allen.library.SuperTextView;

import java.math.BigDecimal;

public class InformationFlowHelper implements  GPSCallback{

    private SuperTextView stv;//用于显示具体数据的文本框

    private GPSManager gpsManager = null;
    private double speed = 0.0;
    Boolean isGPSEnabled = false;
    LocationManager locationManager;
    double currentSpeed, kmphSpeed;//当前实际速度，千米时速
    Context con;
    Activity activity;

    private int minTimeMs = 1000;
    
    public void init(SuperTextView mStv, Context c, Activity ac){
        stv = mStv;
        con = c;
        activity = ac;

        try {
            if (ContextCompat.checkSelfPermission(con, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ac, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getCurrentSpeed() {
        stv.setCenterTopString("速度");
        stv.setCenterBottomString("km/h");
//        stv.setText(getString(R.string.info));
        locationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE);
        gpsManager = new GPSManager(con);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {
            gpsManager.startListening(con);
            gpsManager.setGPSCallback(this);
        } else {
            gpsManager.showSettingsAlert();
        }
    }


    @Override
    public void onGPSUpdate(Location location) {
        speed = location.getSpeed();
        currentSpeed = round(speed, 1, BigDecimal.ROUND_HALF_UP);
        kmphSpeed = round((currentSpeed * 3.6), 1, BigDecimal.ROUND_HALF_UP);
        stv.setCenterString(String.valueOf(kmphSpeed));
    }


    public void onGpsStop() {
        if (gpsManager != null){
            gpsManager.stopListening();
            gpsManager.setGPSCallback(null);
            gpsManager = null;
        }
    }

    //数据的转换
    public static double round(double unrounded, int precision, int roundingMode) {
        BigDecimal bd = new BigDecimal(unrounded);
        BigDecimal rounded = bd.setScale(precision, roundingMode);
        return rounded.doubleValue();
    }

    //更新PM2.5信息
    public void updateAir(){
        stv.setCenterTopString("PM2.5");
        stv.setCenterBottomString("μg/m³");

        stv.setCenterString("36");
    }

}
